#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#define BUFFER_SIZE 1024
int main()
{

    int cfd, i = 0, count = 0, ret;
    struct sockaddr_in servaddr;
    char buf[BUFFER_SIZE];
    char recvbuf[BUFFER_SIZE];
    // 创建socket
    cfd = socket(AF_INET, SOCK_STREAM, 0);
    if (cfd == -1)
    {
        perror("socket error");
        exit(1);
    }

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8080);
    in_addr_t addr;
    inet_pton(AF_INET, "127.0.0.1", &addr);
    servaddr.sin_addr.s_addr = addr; // 可以用 inet_addr("127.0.0.1") 代替inet_pton
    // 连接服务器
    ret = connect(cfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    if (ret < 0)
    {
        perror("connect error");
        exit(1);
    }

    // 发送数据
    while (i++ < 10)
    {
        printf("请输入要发送的数据：");
        scanf("%s", buf);
        write(cfd, buf, strlen(buf));
        count = read(cfd, recvbuf, BUFFER_SIZE);
        if (count < 0)
        {
            perror("read error");
            exit(1);
        }
        printf("接收到的数据为：%s\n", recvbuf);
        memset(recvbuf, 0, BUFFER_SIZE);
        memset(buf, 0, BUFFER_SIZE);
    }
}